#include "comFunction.h"
#include "stdarg.h"
#include "string.h"

/**
 * @brief 返回小的数
 *
 * @param a
 * @param b
 * @return int16_t
 */
int16_t func_min(int16_t a, int16_t b)
{
    if (a > b)
        return b;
    else
        return a;
}

/**
 * @brief 提供10^n
 *
 * @param n
 * @return uint32_t
 */
static uint32_t func_e(uint8_t n)
{
    uint32_t ret = 1;
    for (n; n > 0; n--)
    {
        ret *= 10;
    }
    return ret;
}

/**
 * @brief 字符串转数字
 *
 * @param str 输入字符串
 * @param len 需要转换的长度
 * @return int16_t
 */
int16_t func_str2int(uint8_t *str, uint8_t len)
{
    uint8_t i = 0, hex = 0;
    int16_t ret = 0;
    len = func_min(strlen(str), len); // 防止比字符串长导致发生未定义事件
    for (i = 0; i < len; i++)
    {
        hex = *(str + len - i - 1);
        if (hex == '-')
        {
            ret *= -1;
        }
        if (hex >= '0' && hex <= '9') // 不属于数字
        {
            ret += hex * func_e(i);
        }
    }
    return ret;
}

/**
 * @brief 有符号数字转字符串
 *
 * @param str 目标字符串指针
 * @param num 目标数字
 * @param len 字符串长度，包含符号
 * @return uint8_t*
 */
uint8_t * func_int2str(uint8_t *str, int32_t num, uint8_t len)
{
	uint8_t i = 0;
    if (len == 0)
        return str;
    if (num < 0) // 提前负号
        *(str + 0) = '-';
    for (i = 0; i < len - 1; i++)
    {
        *(str + len - i - 1) = '0' + num % 10;
        num /= 10;
    }
    *(str + len) = '\0';
    return str;
}

/**
 * @brief 无符号数字转字符串
 *
 * @param str 目标字符串指针
 * @param num 目标数字
 * @param len 字符串长度，包含符号
 * @return uint8_t*
 */
uint8_t *func_uint2str(uint8_t *str, int32_t num, uint8_t len)
{
    uint8_t i = 0;
    *(str + len) = '\0';
    if (len == 0)
        return str;
    for (i = 0; i < len; i++)
    {
        *(str + len - i - 1) = '0' + num % 10;
        num /= 10;
    }
    return str;
}

/**
 * @brief 快速平方根倒数
 *
 * @param number
 * @return float
 */
float func_Qrsqrt(int32_t number)
{
    long i;
    float x2, y;
    const float threehalfs = 1.5F;

    x2 = (float)number * 0.5F;
    y = (float)number;
    i = *(long *)&y;           // evil floating point bit level hacking
    i = 0x5f3759df - (i >> 1); // what the fuck?
    y = *(float *)&i;
    y = y * (threehalfs - (x2 * y * y)); // 1st iteration
    y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed

    return y;
}
